package logic

import (
	"context"
	"errors"
	"goods_srv/models"
	"goods_srv/pkg"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *goods.LoginRequest) (*goods.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var err error

	var u models.User
	u.Mobile = in.Mobile
	err = u.GetUser()
	if err != nil {
		logx.Error("查询用户失败")
		return nil, errors.New("查询用户失败")
	}

	if u.ID == 0 {
		u.Mobile = in.Mobile
		u.Password = pkg.Md5(in.Password)
		err = u.Create()
		if err != nil {
			logx.Error("用户注册失败")
		}
	} else {

		if u.Password != pkg.Md5(in.Password) {
			logx.Error("登录失败")
			return nil, errors.New("登录失败")
		}

	}

	return &goods.LoginResponse{
		UserId: int64(u.ID),
	}, nil
}
